/*
 * Copyright (c) 2015, 张涛.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tchintech.pay.frame.presenter;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;


import com.google.gson.Gson;
import com.rey.material.widget.SnackBar;


import com.tchintech.pay.MyApplication;
import com.tchintech.pay.base.MySwipeBackActivity;
import com.tchintech.pay.frame.view.IDelegate;
import com.tchintech.pay.interfaces.HttpResultState;
import com.tchintech.pay.model.entity.HttpCode;
import com.tchintech.pay.model.entity.Memberinfo;
import com.tchintech.pay.net.HttpRequester;
import com.tchintech.pay.net.ResultCallback;
import com.tchintech.pay.utils.SPUtils;

import java.io.File;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.sms.SMSSDK;


/**
 * Presenter base class for Activity
 * Presenter层的实现基类
 *
 * @param <T> View delegate class type
 * @author kymjs (http://www.kymjs.com/) on 10/23/15.
 */
public abstract class ActivityPresenter<T extends IDelegate> extends MySwipeBackActivity implements ResultCallback, HttpResultState {
    protected T viewDelegate;
    public ProgressDialog pd;
    protected SPUtils spUtils;
    protected Context context;
    protected Gson gson;

    public ActivityPresenter() {
        try {
            viewDelegate = getDelegateClass().newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException("create IDelegate error");
        } catch (IllegalAccessException e) {
            throw new RuntimeException("create IDelegate error");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //  hideNavigationBar();

        super.onCreate(savedInstanceState);
        viewDelegate.create(getLayoutInflater(), null, savedInstanceState);
        setContentView(viewDelegate.getRootView());
        gson = new Gson();
        initToolbar();
        viewDelegate.initWidget();
        bindEvenListener();
        context = this;
        spUtils = new SPUtils(context);
        initData();
        initView();
        //极光短信  初始化短信发送
        SMSSDK.getInstance().initSdk(this);
        //极光短信 设置时间间隔
        SMSSDK.getInstance().setIntervalTime(60 * 1000);

    }

    protected Gson getGson() {
        return gson;
    }

    protected void initView() {

    }

    /**
     * 隐藏软键盘
     **/
    protected void hideSoft() {

        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }

    }


    protected void initData() {

    }


    protected void bindEvenListener() {
    }

    public SPUtils getSpUtils() {
        return spUtils;
    }

    protected void initToolbar() {
        Toolbar toolbar = viewDelegate.getToolbar();
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (viewDelegate == null) {
            try {
                viewDelegate = getDelegateClass().newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException("create IDelegate error");
            } catch (IllegalAccessException e) {
                throw new RuntimeException("create IDelegate error");
            }
        }
    }

    public void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (viewDelegate.getOptionsMenuId() != 0) {
            getMenuInflater().inflate(viewDelegate.getOptionsMenuId(), menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewDelegate = null;
    }

    public void showSnackBar(String message) {
        SnackBar.make(this).actionText(message).duration(Snackbar.LENGTH_SHORT).show();
    }

    protected abstract Class<T> getDelegateClass();

    public Memberinfo getMemberinfo() {
        return ((MyApplication) getApplication()).getMemberinfo();
    }

    /**
     * 需要传设备信息.所有的activity需要.
     *
     * @return
     */
    public TelephonyManager getTelephonyManager() {
        return ((TelephonyManager) getSystemService(TELEPHONY_SERVICE));
    }

    public void showProgressDialog(String title, String text) {
        pd = ProgressDialog.show(this, title, text);
    }

    public void hideProgressDialog() {
        if (pd != null) {
            pd.dismiss();
        }
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HttpCode.http_failed:
                    showMsg("请求超时");
                    break;
            }


        }
    };

    @Override
    public void httpCallback(String resultBean, int what) {
        if (resultBean.equals("")) {
            handler.sendEmptyMessage(HttpCode.http_failed);
        }
        handler.sendEmptyMessage(what);
        hideProgressDialog();
    }

    public void httpPost(String url, Map<String, String> map, int what, File file) {
        String path = HttpRequester.path(url, map);
        try {
            hideSoft();
            showProgressDialog("", "加载中，请稍后...");
            HttpRequester.post(this, what, path, map, this, file);
        } catch (Exception e) {
            hideProgressDialog();
        }
    }
}

